﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using 多协议通信平台.Entity;

namespace 多协议通信平台.Common
{
    public class ListItemTemplateSelector : DataTemplateSelector
    {
        private ResourceDictionary resourceDict;

        private static Dictionary<string, DataTemplate> CacheDict = new Dictionary<string, DataTemplate>();

        public ListItemTemplateSelector()
        {
            resourceDict = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Contains("ModbusSendTemplate"));
            if (resourceDict == null)
            {
                throw new Exception("数据模板不能为空");
            }
        }

        // 定义不同的模板（可在XAML或代码中赋值）(弃用)
        public DataTemplate SendTemplate { get; set; }
        public DataTemplate NormalRecvTemplate { get; set; }
        public DataTemplate ErrorRecvTemplate { get; set; }



        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            string key;
            // 根据数据对象的属性选择模板
            if (item is Data_ModbusLog data)
            {
                switch (data.MsgType)
                {
                    case "Send":
                        key = "ModbusSendTemplate";
                        if (!CacheDict.ContainsKey(key))
                        {
                            DataTemplate dataTemplate = (DataTemplate)resourceDict[key];
                            CacheDict.Add(key, dataTemplate);
                        }
                        return CacheDict[key];
                    case "Recv":
                        if (data.Status == 0)
                        {
                            key = "ModbusNormalRecvTemplate";
                        }
                        else
                        {
                            key = "ModbusErrorRecvTemplate";
                        }
                        if (!CacheDict.ContainsKey(key))
                        {
                            DataTemplate dataTemplate = (DataTemplate)resourceDict[key];
                            CacheDict.Add(key, dataTemplate);
                        }
                        return CacheDict[key];
                    default:
                        break;
                }
            }
            return null; // 默认返回null会使用默认模板
        }
    }
}
